#include <stdio.h>
#include <string.h>

#define BUFSIZE 1000
char s1[BUFSIZE] = "hello";
char s2[BUFSIZE] = "hello";

char *strncpy2(char *s, const char *ct, size_t n)
{
    size_t len = strlen(ct);
    char *p = s;
    if(len < n) n = len;
    while(n--)
    {
        *p++ = *ct++;
    }
    *p = '\0';
    return s;    
}

char *strncat2(char *s, const char *ct, size_t n)
{
    size_t len = strlen(ct);
    char *p = s;
    if(len < n) n = len;
    while (*p) p++;    
    while(n--)
    {
        *p++ = *ct++;
    }
    *p = '\0';
    return s;    
}

int strncmp2(const char *cs, const char *ct, size_t n)
{
    size_t len = strlen(cs);
    if(len < n) n = len;
    
    for(; *cs == *ct; cs++, ct++, n--)
    {
        if(n == 0) return 0;
    }

    if(*cs > *ct) return 0;
    
    return *cs - *ct;    
}

int main()
{
    const char *t = "world";

    char *out1 = strncpy2(s1, t, 10);
    printf("out1=%s\n", out1);

    char *out2 = strncpy2(s1, t, 5);
    printf("out2=%s\n", out2);

    char *out3 = strncat2(s2, t, 3);
    printf("out3=%s\n", out3);

    char *out4 = strncat2(s2, t, 12);
    printf("out4=%s\n", out4);

    printf("cmp2 = %d\n", strncmp2("hello", "world", 2));
    printf("cmp = %d\n", strncmp("hello", "world", 2));

    printf("cmp2 = %d\n", strncmp2("hello", "helloworld", 2));
    printf("cmp = %d\n", strncmp("hello", "helloworld", 2));

    printf("cmp2 = %d\n", strncmp2("hello", "helloworld", 8));
    printf("cmp = %d\n", strncmp("hello", "helloworld", 8));

    return 0;
}